<?php

/**
 * @author gbfun <gbfun@163.com>  2018-04-15 20:49
 * http://www.wuweiyou.com
 */

class db_table_good_category extends wwy_db_table
{
    protected $_name = 'good_good_category';
    
    protected static $_instance;
    
    public static function get_instance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();    //by gbfun 又是静态变量
        }
    
        return self::$_instance;
    }
    
    public function find($id)
    {
        $read_db = $this->_get_read_db();
    
        $sql = '
            SELECT id, parent_id, name, `order`, status, create_time, update_time 
            FROM ' . $this->_full_name . '
            WHERE id = ?;
        ';
        $row = $read_db->fetch_row($sql, $id);
    
        return $row;
    }
    
    public function fetch_all($where = null, $order = null, $count = null, $offset = null)
    {
        $read_db = $this->_get_read_db();
    
        $where_str = '';
        $where_bind = array();        
        if(isset($where['ids'])){
            $ids = $read_db->quote($where['ids']);
            $where_str .= 'id IN (' . $ids . ')';
        }
        
        if(isset($where['not_in_ids'])){
            $ids = $read_db->quote($where['not_in_ids']);
            $where_str .= 'id NOT IN (' . $ids . ')';
        }
        
        if(isset($where['parent_id'])){
            if($where_str != ''){
                $where_str .= 'AND ';
            }
            $where_str    .= 'parent_id = ? ';
            $where_bind[]  = $where['parent_id'];
        }
        
        if(isset($where['status'])){
            if($where_str != ''){
                $where_str .= 'AND ';
            }
            $where_str    .= 'status = ? ';
            $where_bind[]  = $where['status'];
        }
    
        if($where_str != ''){
            $where_str = 'WHERE ' . $where_str;
        }
    
        $order_str = '';
        if($order !== null){
            if(!is_array($order)){
                $order = array($order);
            }
            $order_str = 'ORDER BY ' . implode(', ', $order) . ' ';
        }
    
        $sql = '
            SELECT `id`, `parent_id`, `name`, `order`, `status`, `create_time`, `update_time`
            FROM ' . $this->_full_name . '
            ' . $where_str . '
            ' . $order_str . '
        ';
    
        if($count !== null){
            $sql = $read_db->limit($sql, $count, $offset);
        }
    
        $rows = $read_db->fetch_all($sql, $where_bind);
    
        return $rows;
    }
}

